<template>
  <div class="w-full h-full fatherMap">
    <div id="baseMap" class="w-full h-full z-2"></div>
    <!-- <div class="search">
      <a-input-search
        v-model:value="searchValue"
        placeholder="请输入搜索信息"
        enter-button
        size="large"
        @search="onSearch"
      />
    </div> -->
  </div>
</template>

<script setup lang="ts" name="home">
import * as L from 'leaflet'
import 'leaflet/dist/leaflet.css'
import { onMounted, onBeforeUnmount, ref } from 'vue'
import { getAssetURL } from '@/utils/load_assets_img'
import axios from 'axios'
interface IDataItem {
  id: number
  name: string
  icon: any
  position: number[]
  layerPopup: any
}
/* 解决缩放报错 */
L.Popup.prototype._animateZoom = function (e) {
  if (!this._map) {
    return
  }
  let pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center),
    anchor = this._getAnchor()
  L.DomUtil.setPosition(this._container, pos.add(anchor))
}

/* 标记数据 */
const mapRef = ref() //地图实例
let mapLayerGroup: any = null
/* 对话框 */
const popup = L.popup()

/* 设置地图可拖动边界 */

const corner1 = L.latLng(30.093231938356592, 120.27992963790895)
const corner2 = L.latLng(30.075648935286814, 120.31861782073976)
const bounds = L.latLngBounds(corner1, corner2)
onMounted(() => {
  // 创建地图实例，将其绑定到 id 参数为 "map" 的 DOM 元素上※
  mapRef.value = L.map('baseMap', {
    attributionControl: false,
    crs: L.CRS.EPSG3857,
    maxBounds: bounds,
    closePopupOnClick: false,
    zoomAnimation: false
  })

  // 使用 setView() 方法设置地图中心点坐标（维度，经度）和初始缩放级别※
  mapRef.value.setView([30.085916897591254, 120.29802918434144], 17)

  //加入图层并添加到地图

  mapLayerGroup = L.layerGroup([
    L.tileLayer(
      'http://t0.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=a4aa556d019c2920f0d01352a23c93e4',
      {
        minZoom: 16,
        maxZoom: 22,
        tms: false,
        attribution: '高德地图卫星图'
      }
    ),
    // 'http://192.168.191.145:5173/src/assets/img_4/{z}/{x}/{y}.png'
    L.tileLayer(
      'https://cf.zealwin.cn:8105/cmap/{z}/{x}/{y}.png',
      // 'http://192.168.190.148:121/home/deploy/chaungfangMap/staticImg/tiles/{z}/{x}/{y}.png',
      // 'http://192.168.191.145:5173/src/assets/img_4/{z}/{x}/{y}.png',
      {
        minZoom: 16,
        maxZoom: 22,
        tms: false,
        attribution: '传芳村航拍实景图'
      }
    )
  ]).addTo(mapRef.value)
  //加入点击事件
  //增加其他地图

  mapRef.value.on('click', onMapClick)
  //监听缩放
  // mapRef.value.on('zoomend', (e: any) => {

  // })
  //加入标记

  // L.circle([30.07062175859118, 120.30229537776827], {
  //   radius: 100,
  //   color: '#ff0000',
  //   weight: 5,
  //   fill: true,
  //   fillColor: '#00ff00',
  //   fillOpacity: 1
  // }).addTo(mapRef.value)

  // fetchHouseIconData()
})
/* 获取图标信息 */
let iconArr: any[] = []
let iconDetail: any = {}
async function fetchHouseIconData(type: string = 'scenic', id?: number) {
  const res = await axios({
    method: 'get',
    url: 'https://cf.zealwin.cn:8105/screen/building_site/list',
    params: {
      type,
      id
    }
  })
  removeIcon()
  iconArr = res.data.data
  iconArr.forEach((item) => {
    if (item.latitude && item.longitude) {
      let houseIcon = L.icon({
        iconUrl: item.iconUrl,
        iconSize: [181, 129]
      })
      addMarkerIcon([item.latitude, item.longitude], houseIcon, item.site, item.id)
    }
  })
  if (id) {
    const newLocation = L.latLng(iconArr[0].latitude, iconArr[0].longitude)
    mapRef.value.panTo(newLocation)
  }
}
/* 删除图标 */
function removeIcon() {
  if (iconArr.length > 0) {
    iconArr.forEach((item) => {
      if (item.layerPopup) {
        mapRef.value.removeLayer(item.layerPopup)
      }
    })
  }
}
/* 增加图标 */
function addMarkerIcon(position: any, icon: any, info: string, id: number) {
  console.log(icon, 'gagag')
  const curItem = iconArr.find((item) => item.id === id)
  if (curItem) {
    curItem['layerPopup'] = L.marker(position, {
      icon
    })
      .bindPopup(info, { autoClose: false, closeOnClick: false })
      .addTo(mapRef.value)
      .on('click', clickMarker)
      .openPopup()
  }
}
function onMapClick(e: any) {
  popup
    .setLatLng(e.latlng)
    .setContent(`纬度:${e.latlng.lat},经度:${e.latlng.lng}`)
    .openOn(mapRef.value)
  // L.marker(e.latlng).bindPopup(`纬度:${e.latlng.lat},经度:${e.latlng.lng}`).addTo(mapRef.value)
}
function clickMarker(e: any) {
  console.log('点击标记', e, e.latlng.lat, e.latlng.lng)
  const newLocation = L.latLng(e.latlng.lat, e.latlng.lng)
  // mapRef.value.panTo(newLocation)
  mapRef.value.setView(newLocation, 22)
  const curItem = iconArr.find(
    (item) => item.latitude == e.latlng.lat && item.longitude == e.latlng.lng
  )
  curItem.layerPopup.openPopup()

  emitInfo(curItem)
}
/** 卸载地图 */
onBeforeUnmount(() => {
  mapRef.value.remove()
})

/* iframe之间通信 */
// 子页面接收信息
window.addEventListener(
  'message',
  function (e) {
    if (e.data) {
      if (e.data.type) {
        fetchHouseIconData(e.data.type, e.data.id)
      }
    }
  },
  false
)
/* 向父页面发送消息 */
function emitInfo(payload: any) {
  if (window) {
    console.log(payload.id)
    window.parent.postMessage(payload.id, '*')
  }
}
</script>

<style lang="less" scoped>
.fatherMap {
  position: relative;
  // background: pink;
  #baseMap {
    background-color: transparent;
  }
  .search {
    position: absolute;
    top: 18px;
    left: 75px;
    z-index: 3;
  }
  .z-2 {
    position: absolute;
    z-index: 2;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
  }
  .z-1 {
    position: absolute;
    z-index: 1;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    background-color: blue;
  }
}
.w-full {
  width: 100%;
}
.h-full {
  height: 100%;
}
// :deep(.leaflet-popup-content-wrapper) {
//   background-color: rgba(255, 255, 255, 0.5);
// }
</style>
